// 认证相关工具函数
import request from "./request.js"

const TOKEN_KEY = "token"
const USER_INFO_KEY = "user_info"

// 检查登录状态
export function checkLoginStatus() {
  return new Promise((resolve) => {
    const token = uni.getStorageSync(TOKEN_KEY)
    const userInfo = uni.getStorageSync(USER_INFO_KEY)

    // 同时验证token和用户信息存在
    const isLoggedIn = !!token && !!userInfo
    
    // 同步更新Vuex登录状态
    if (getApp().$store) {
      getApp().$store.commit('SET_LOGIN_STATUS', isLoggedIn);
      if (userInfo) {
        try {
          getApp().$store.commit('SET_USER_INFO', JSON.parse(userInfo));
        } catch (e) {
          console.error('解析用户信息失败', e);
        }
      }
    }

    resolve(isLoggedIn)
  })
}

// 获取用户信息
export function getUserInfo() {
  return new Promise((resolve, reject) => {
    const userInfo = uni.getStorageSync(USER_INFO_KEY)

    if (userInfo) {
      try {
        resolve(JSON.parse(userInfo))
      } catch (error) {
        reject(new Error("用户信息解析失败"))
      }
    } else {
      reject(new Error("用户信息不存在"))
    }
  })
}

// 获取微信小程序登录code
export function getWechatCode() {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: "weixin",
      success: (res) => {
        if (res.code) {
          resolve(res.code)
        } else {
          reject(new Error("获取微信code失败"))
        }
      },
      fail: (error) => {
        reject(new Error("微信登录授权失败"))
      },
    })
  })
}

// 获取用户授权信息
export function getUserProfile() {
  return new Promise((resolve, reject) => {
    // #ifdef MP-WEIXIN
    uni.getUserProfile({
      desc: "用于完善用户资料",
      success: (res) => {
        resolve(res.userInfo)
      },
      fail: (error) => {
        reject(new Error("获取用户信息失败"))
      },
    })
    // #endif

    // #ifndef MP-WEIXIN
    uni.getUserInfo({
      success: (res) => {
        resolve(res.userInfo)
      },
      fail: (error) => {
        reject(new Error("获取用户信息失败"))
      },
    })
    // #endif
  })
}

// 微信小程序登录
export async function wechatMiniLogin() {
  try {
    // 1. 获取微信登录code
    const code = await getWechatCode()

    // 2. 获取用户授权信息
    // const userProfile = await getUserProfile()
    console.log(code, 'getWechatCode');

    // 3. 调用登录接口
    const loginResult = await request.httpRequest({
      url: "/api/user/xcx_login",
      method: "post",
      data: {
        code: code
      }
    }, )
    console.log(loginResult, '/api/user/xcx_login');


    if (loginResult.data.code == 1) {
      // 保存token和用户信息
      const {
        userinfo,
        
      } = loginResult.data.data
      uni.setStorageSync(TOKEN_KEY, userinfo.token)
      uni.setStorageSync(USER_INFO_KEY, JSON.stringify(userinfo))

      return {
        success: true,
        userInfo: userinfo,
        token: userinfo.token,
      }
    } else {
      throw new Error(loginResult.data.message || "登录失败")
    }
  } catch (error) {
    // 如果真实接口失败，使用模拟登录
    console.warn("真实登录失败，使用模拟登录:", error.message)
    return mockWechatLogin()
  }
}

// 手机号登录
export async function phoneLogin(phone, code) {
  try {
    const loginResult = await request.httpRequest({
      url: "api/auth/phone/login",
      method: "post",
    }, {
      phone: phone,
      code: code,
      platform: "miniprogram",
    }, )

    if (loginResult.data.code === 200) {
      const {
        token,
        userInfo
      } = loginResult.data.data
      uni.setStorageSync(TOKEN_KEY, token)
      uni.setStorageSync(USER_INFO_KEY, JSON.stringify(userInfo))

      return {
        success: true,
        userInfo: userInfo,
        token: token,
      }
    } else {
      throw new Error(loginResult.data.message || "登录失败")
    }
  } catch (error) {
    // 如果真实接口失败，使用模拟登录
    console.warn("真实登录失败，使用模拟登录:", error.message)
    return mockPhoneLogin(phone)
  }
}

// 获取用户详细信息
export async function fetchUserInfo() {
  try {
    const result = await request.httpTokenRequest({
      url: "/api/user/getUserInfo",
      method: "get",
    })

    if (result.data.code === 1) {
      console.log(result.data.data, '获取用户信息成功');

      // 更新本地用户信息
      const userInfo = result.data.data.user_info
      userInfo.user_coupon_count = result.data.data.user_coupon_count
      uni.setStorageSync(USER_INFO_KEY, JSON.stringify(userInfo))
      return result.data.data
    } else {
      throw new Error(result.data.message || "获取用户信息失败")
    }
  } catch (error) {
    console.warn("获取用户信息失败:", error.message)
    // 返回本地缓存的用户信息
    return getUserInfo()
  }
}

// 模拟微信登录（备用方案）
function mockWechatLogin() {
  return new Promise((resolve) => {
    setTimeout(() => {
      const mockUserInfo = {
        id: Date.now(),
        nickName: "微信用户" + Math.floor(Math.random() * 1000),
        avatarUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132",
        description: "这个人很神秘，什么都没有写",
        phone: "",
        loginType: "wechat",
        gender: 1,
        city: "深圳",
        province: "广东",
      }

      const mockToken = generateToken(mockUserInfo.id)

      uni.setStorageSync(TOKEN_KEY, mockToken)
      uni.setStorageSync(USER_INFO_KEY, JSON.stringify(mockUserInfo))

      resolve({
        success: true,
        userInfo: mockUserInfo,
        token: mockToken,
      })
    }, 1500)
  })
}

// 模拟手机登录（备用方案）
function mockPhoneLogin(phone) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const mockUserInfo = {
        id: Date.now(),
        nickName: "手机用户" + phone.slice(-4),
        avatarUrl: "/static/default-avatar.png",
        description: "这个人很神秘，什么都没有写",
        phone: phone,
        loginType: "phone",
        gender: 0,
        city: "",
        province: "",
      }

      const mockToken = generateToken(mockUserInfo.id)

      uni.setStorageSync(TOKEN_KEY, mockToken)
      uni.setStorageSync(USER_INFO_KEY, JSON.stringify(mockUserInfo))

      resolve({
        success: true,
        userInfo: mockUserInfo,
        token: mockToken,
      })
    }, 1500)
  })
}

// 登出
export function logout() {
  return new Promise((resolve) => {
    // 调用登出接口
    request
      .httpTokenRequest({
        url: "api/auth/logout",
        method: "post",
      })
      .finally(() => {
        clearUserData()
        resolve(true)
      })
  })
}

// 生成模拟token
function generateToken(userId) {
  const expireTime = Date.now() + 7 * 24 * 60 * 60 * 1000 // 7天过期
  const tokenData = {
    userId,
    expireTime,
    timestamp: Date.now(),
  }

  return btoa(JSON.stringify(tokenData))
}

// 清除用户数据
function clearUserData() {
  uni.removeStorageSync(TOKEN_KEY)
  uni.removeStorageSync(USER_INFO_KEY)
}

// 获取token
export function getToken() {
  return uni.getStorageSync(TOKEN_KEY)
}

// 设置token
export function setToken(token) {
  uni.setStorageSync(TOKEN_KEY, token)
}

// 在文件末尾，确保所有函数都被导出